/**
 * 
 */
package com.pos.set.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;

import com.pos.set.Log;

import java.util.ArrayList;

/**
 * @description: 历史搜索记录provider
 * @author: jacky.cai
 * @time:2016年8月11日上午11:48:05
 */
public class HangGoodsProvider extends ContentProvider {

	public static final String AUTHORITY = "hang.goods_pos_sec";
	public static final String TABLE_NAME = "goods";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE_NAME);

	private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

	private static final int GOODS = 1;
	private static final int GOODS_ID = 2;

	static {
		URI_MATCHER.addURI(AUTHORITY, "goods", GOODS);
		URI_MATCHER.addURI(AUTHORITY, "goods/#", GOODS_ID);
	}

	private static final String TAG = "HangGoodsProvider";

	private SQLiteOpenHelper mOpenHelper;

	public HangGoodsProvider() {
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new GoodsDatabaseHelper(getContext());
		return true;

	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

		SQLiteQueryBuilder qBuilder = new SQLiteQueryBuilder();
		int match = URI_MATCHER.match(uri);

		switch (match) {
		case GOODS:
			qBuilder.setTables(TABLE_NAME);
			break;
		case GOODS_ID:
			qBuilder.setTables(TABLE_NAME);
			qBuilder.appendWhere("_id=");
			qBuilder.appendWhere(uri.getPathSegments().get(1));
			break;
		default:
			throw new IllegalArgumentException("Unknown URL " + uri);
		}

		String orderBy;
		if (TextUtils.isEmpty(sortOrder)) {
			orderBy = GoodsConstants.DEFAULT_SORT_ORDER;
		} else {
			orderBy = sortOrder;
		}

		SQLiteDatabase db = mOpenHelper.getReadableDatabase();
		Cursor ret = qBuilder.query(db, projection, selection, selectionArgs, null, null, orderBy);

		if (ret == null) {
			Log.e(TAG, "HangGoodsProvider.query: failed");
		} else {
			ret.setNotificationUri(getContext().getContentResolver(), uri);
		}

		return ret;

	}

	@Override
	public String getType(Uri uri) {

		int match = URI_MATCHER.match(uri);
		switch (match) {
		case GOODS:
			return GoodsConstants.CONTENT_TYPE;
		case GOODS_ID:
			return GoodsConstants.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URL");
		}

	}

	@Override
	public Uri insert(Uri url, ContentValues initialValues) {
		if (URI_MATCHER.match(url) != GOODS) {
			throw new IllegalArgumentException("Cannot insert into URL: " + url);
		}

		ContentValues values = (initialValues != null) ? new ContentValues(initialValues) : new ContentValues();

		for (String colName : GoodsConstants.getRequiredColumns()) {
			if (values.containsKey(colName) == false) {
				Log.e("HangGoodsProvider insert", "Missing column:" + colName);
				Log.e("HangGoodsProvider insert", "Missing column:" + colName);
				throw new IllegalArgumentException("Missing column: " + colName);

			}
		}

		SQLiteDatabase db = mOpenHelper.getWritableDatabase();

		long rowId = db.insert(TABLE_NAME, GoodsConstants.DATE, values);

		if (rowId < 0) {
			throw new SQLException("Failed to insert row into " + url);
		}

		Uri noteUri = ContentUris.withAppendedId(CONTENT_URI, rowId);
		getContext().getContentResolver().notifyChange(noteUri, null);
		return noteUri;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {

		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (URI_MATCHER.match(uri)) {

		case GOODS:
			count = db.delete(TABLE_NAME, selection, selectionArgs);
			break;
		case GOODS_ID:
			String segment = uri.getPathSegments().get(1);
			if (TextUtils.isEmpty(selection)) {
				selection = "_id=" + segment;
			} else {
				selection = "_id=" + segment + " AND (" + selection + ")";
			}
			count = db.delete(TABLE_NAME, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Cannot delete from URL: " + uri);
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;

	}

	@Override
	public int update(Uri url, ContentValues values, String where, String[] whereArgs) {

		int count;
		long rowId = 0;
		int match = URI_MATCHER.match(url);
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();

		switch (match) {
		case GOODS:
			count = db.update(TABLE_NAME, values, where, whereArgs);
			break;
		case GOODS_ID:
			String segment = url.getPathSegments().get(1);
			rowId = Long.parseLong(segment);
			count = db.update(TABLE_NAME, values, "_id=" + rowId, null);
			break;
		default:
			throw new UnsupportedOperationException("Cannot update URL: " + url);
		}
		Log.e(TAG, "*** notifyChange() rowId: " + rowId + " url " + url);

		getContext().getContentResolver().notifyChange(url, null);
		return count;

	}

	private static class GoodsDatabaseHelper extends SQLiteOpenHelper {
		private static final String Tag = "GoodsDatabaseHelper";

		private static final String DATABASE_NAME = "goods.db";
		private static final int DATABASE_VERSION = 1;

		public GoodsDatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.e(Tag, "creating goods table");

			db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + GoodsConstants._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
					+ GoodsConstants.DATE + " INTEGER," + GoodsConstants.NAME + " TEXT," + GoodsConstants.GOODS
					+ " TEXT," + GoodsConstants.REMARK + " TEXT);");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.e(Tag, "onUpgrade: from " + oldVersion + " to " + newVersion);
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
			onCreate(db);
		}

	}

	public static final class GoodsConstants implements BaseColumns {

		private GoodsConstants() {
		}

		public static final String CONTENT_TYPE = "smartpos.dir/smartpos.goods";
		public static final String CONTENT_ITEM_TYPE = "smartpos.item/smartpos.goods";
//		public static final String DEFAULT_SORT_ORDER = "_id ASC"; // sort by auto-id
		public static final String DEFAULT_SORT_ORDER = "date DESC"; // sort by auto-id

		public static final String DATE = "date";
		public static final String NAME = "name";

		public static final String GOODS = "goods";
		/**
		 * 备注（预留字段）
		 */
		public static final String REMARK = "remark";

		public static ArrayList<String> getRequiredColumns() {
			ArrayList<String> tmpList = new ArrayList<String>();
			tmpList.add(DATE);
			tmpList.add(NAME);
			tmpList.add(GOODS);
			return tmpList;
		}

	}

}
